<?php

namespace app\api\controller;

use think\App;
use think\facade\Cache;
use think\facade\Env;

/**
 * 微信小程序
 */
class WMinapp
{
    //生成二维码
    //order 绑定订单
    //user  绑定用户关系
    public function get_qrcode($type = 'order', $sid = 1, $path=''){
        $APPID = Env::get('WX_APPID'); 
        $APPSECRET =  Env::get('WX_SECRET'); 
        if ($type == 'order') {
            $path = 'pages/order/order';
        } else {
            $path = 'pages/index/index';
        }
        $ACCESS_TOKEN = $this->get_accesstoken($APPID, $APPSECRET);
        $qcode ="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$ACCESS_TOKEN";
        $param = json_encode(array("path"=>$path."?type=$type"."&sid=".$sid,"width"=>150));
        //POST参数
        $result = $this->httpRequest( $qcode, $param,"POST");
        $base64_image = "data:image/jpeg;base64,".base64_encode( $result );
        $this->mkdirs('uploads/qrcode/');
        $new_name = $this->base64_save($base64_image,'uploads/qrcode/');
         $hppt = is_https() ? 'https' : 'http';
         $url = $hppt . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/' . 'uploads/qrcode/' . $new_name;
         return $url;
    }

    public function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!$this->mkdirs(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }

    public function get_accesstoken($APPID, $APPSECRET)
    {
        //获取access_token
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
        //缓存access_token
        $ACCESS_TOKEN = Cache::get('xcx_access_token');
        if (empty($ACCESS_TOKEN)) {
            $json = $this->httpRequest( $access_token );
            $json = json_decode($json,true); 
            $ACCESS_TOKEN = $json['access_token'];
            Cache::set('xcx_access_token', $ACCESS_TOKEN, 3600);
        }
        return $ACCESS_TOKEN;
    }

    //把请求发送到微信服务器换取二维码
    public function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();  
        curl_setopt($curl, CURLOPT_URL, $url);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);  
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);  
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);  
        if($method=='POST'){
            curl_setopt($curl, CURLOPT_POST, 1); 
            if ($data != ''){
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
            }
        }
        
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);  
        curl_setopt($curl, CURLOPT_HEADER, 0);  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
        $result = curl_exec($curl);  
        curl_close($curl);  
        return $result;
    }

    /*
    * 保存base64格式图片到指定文件夹中
    * $base64_img 图片数据
    * $path 要保存到的图片地址
    */ 
   public function base64_save($base64_img,$path){
        $img_base = str_replace('data:image/jpeg;base64,', '', $base64_img);
        $img_name = time().rand(1000,9999).'.jpg'; //图片新名称
        $img_path = $path.$img_name;
        file_put_contents($img_path,base64_decode($img_base));
        
        return $img_name; //返回新名称
    }
}